interface UseCountDownReturn {
    days: Ref<number>
    hours: Ref<number>
    minutes: Ref<number>
    seconds: Ref<number>
    isActive: Ref<boolean>
    start: () => void
    stop: () => void
    setTargetTime: (t: any) => void
}

/**
 * 倒计时 Hook
 * @param targetTime - 目标时间戳（未来时间）
 * @param callback - 倒计时结束后的回调函数
 */
export default function useCountdown(targetTime: number, callback?: () => void): UseCountDownReturn {
    const days = ref<number>(0)
    const hours = ref<number>(0)
    const minutes = ref<number>(0)
    const seconds = ref<number>(0)
    const isActive = ref<boolean>(false)
    const targetTimeRef = ref<number>(targetTime)
    let intervalId: ReturnType<typeof setInterval> | null = null
    const setTargetTime = (t: any) => {
        targetTimeRef.value = t
    }
    const updateCountdown = () => {
        const now = Date.now()
        const distance = Math.max(targetTimeRef.value - now, 0)
        if (distance === 0) {
            days.value = hours.value = minutes.value = seconds.value = 0
            if (isActive.value && callback) {
                callback()
            }
            stop()
            return
        }

        days.value = Math.floor(distance / (1000 * 60 * 60 * 24))
        hours.value = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
        minutes.value = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
        seconds.value = Math.floor((distance % (1000 * 60)) / 1000)
    }

    const start = () => {
        if (isActive.value) return
        isActive.value = true
        updateCountdown()
        intervalId = setInterval(updateCountdown, 1000)
    }

    const stop = () => {
        if (intervalId) {
            clearInterval(intervalId)
            intervalId = null
        }
        isActive.value = false
    }

    // 组件卸载时自动停止倒计时
    onUnmounted(() => {
        stop()
    })

    return {
        days,
        hours,
        minutes,
        seconds,
        isActive,
        start,
        stop,
        setTargetTime
    }
}
